package com.imdroid.carac.net;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URLEncoder;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.imdroid.carac.IMDroid;
import com.imdroid.carac.net.weibo.Oauth2AccessToken;
import com.imdroid.carac.net.weibo.WeiboAuthListener;
import com.imdroid.carac.net.weibo.WeiboDialog;
import com.imdroid.carac.net.weibo.WeiboDialogError;
import com.imdroid.carac.net.weibo.WeiboException;
import com.imdroid.carac.net.weibo.WeiboParameters;
import com.imdroid.carac.net.weibo.net.HttpManager;

// 本类简单封装了新浪微博接口，主要只用到了新浪sdk里面的 HttpManager （封装了 https 发包功能）和 WeiboDialog （一个网页对话框，用户输帐号登微博）
// com.imdroid.carac.net.weibo 这个包里是 2012-11-1 发布的 sina 官方微博 sdk，有问题，做了几处修改：
// HttpManager.java 里面做了修改，要返回微博的具体错误代码，这样发微博数据的时候才知道是需要登录还是网络错误
// WeiboDialog.java 里面做了修改，重定向地址改为本类下面的 redirect，对话框改大了些，去掉了不需要的资源引用
public class Weibo {

	private static final String appId = "3874678839"; // a.k.a app key
	// private static final String appPassword =
	// "4d5203ae4754595699e243af7be9029c"; // a.k.a app secret, not needed in
	// new version
	public static final String redirect = "http://www.sina.com";
	private static final Oauth2AccessToken token = new Oauth2AccessToken();
	private static final File tokenFile = new File(IMDroid.WEIBO_FOLDER,
			"weiboToken");

	// 开机、通电时，还没显示环境不能显示登录对话框，所以做个标记，在 HomeActiviti.onResume() 里面登录
	public static boolean toAuth;

	static {
		if (tokenFile.isFile()) {
			BufferedReader in = null;
			try {
				in = new BufferedReader(new InputStreamReader(
						new FileInputStream(tokenFile)));
				token.setToken(in.readLine());
				token.setExpiresTime(Long.parseLong(in.readLine()));
			} catch (NumberFormatException e) {
				Log.e(Weibo.class.getName(), "load token", e);
			} catch (FileNotFoundException e) {
				Log.e(Weibo.class.getName(), "load token", e);
			} catch (IOException e) {
				Log.e(Weibo.class.getName(), "load token", e);
			}

			if (in != null)
				try {
					in.close();
				} catch (IOException e) {
					Log.e(Weibo.class.getName(), "load token", e);
				}
		}
	}

	// 快速登录，先检查已有的登录信息能不能用，不能用再转登录页面
	public static void quickAuth(Activity activity) {
		testAndAuth(activity);
	}

	// 强制登录，直接打开登录对话框，用于切换用户等情况
	public static void forceAuth(Activity activity) {
		authAndSend(activity, null, null);
	}

	// 发微博，若未登录则转登录页面，登录成功后再发
	public static void sendAllowAuth(Activity activity, String text,
			String picFile) {
		sendAndAuth(activity, text, picFile, true);
	}

	// 发微博，若未登录则失败
	public static void sendNoAuth(String text, String picFile) {
		sendAndAuth(null, text, picFile, false);
	}

	@SuppressWarnings("deprecation")
	private static void authAndSend(final Activity activity, final String text,
			final String picFile) {
		String url = "https://open.weibo.cn/oauth2/authorize?response_type=token&display=mobile&forcelogin=true";
		url += "&client_id=" + appId;
		url += "&redirect_uri=" + URLEncoder.encode(redirect);
		new WeiboDialog(activity, url, new WeiboAuthListener() {

			public void onComplete(Bundle b) {
				token.setToken(b.getString("access_token"));
				token.setExpiresIn(b.getString("expires_in"));
				PrintWriter out = null;
				try {
					out = new PrintWriter(tokenFile);
				} catch (FileNotFoundException e) {
					Log.e(Weibo.class.getName(), "load token", e);
				}
				if (out != null) {
					out.println(token.getToken());
					out.println(token.getExpiresTime());
					out.close();
				}
				Toast.makeText(IMDroid.getContext(), "微博登录成功!",
						Toast.LENGTH_LONG).show();
//				IMDroid.setWeiboLogin(true);
				sendAndAuth(activity, text, picFile, false);
			}

			public void onCancel() {
				Toast.makeText(IMDroid.getContext(), "微博登录取消",
						Toast.LENGTH_LONG).show();
//				IMDroid.setWeiboLogin(false);
			}

			public void onError(WeiboDialogError e) {
				Log.e(Weibo.class.getName(), "auth dialog error", e);
				Toast.makeText(IMDroid.getContext(),
						"微博登录失败：" + e.getMessage(), Toast.LENGTH_LONG).show();
//				IMDroid.setWeiboLogin(false);
			}

			public void onWeiboException(WeiboException e) {
				Log.e(Weibo.class.getName(), "auth weibo exception", e);
				Toast.makeText(IMDroid.getContext(),
						"微博登录失败：错误号 " + e.getStatusCode(), Toast.LENGTH_LONG)
						.show();
//				IMDroid.setWeiboLogin(false);
			}
			// } );
		}).show();
	}

	private static void sendAndAuth(final Activity activity, final String text,
			final String picFile, final boolean allowAuth) {
		if (text == null)
			return;

		// prepare send data
		final WeiboParameters params = new WeiboParameters();
		params.add("access_token", token.getToken());
		params.add("source", appId);
		params.add("status", text);
		params.add("visible", 2);
		String url = "https://api.weibo.com/2/statuses/";
		if (picFile == null || picFile.equals("")) { // pure text
			url += "update.json";
		} else { // text + picFile
			url += "upload.json";
		}

		final String urlA = url;
		// async send
		new Thread() {
			public void run() {
				WeiboException err = null;
				try {
					HttpManager.openUrl(urlA, "POST", params, picFile);
				} catch (WeiboException e) {
					err = e;
				}

				final WeiboException e = err;
				IMDroid.runInMainLooper(new Runnable() {
					public void run() {
						// send success
						if (e == null) {
							Toast.makeText(IMDroid.getContext(), "微博发送成功!",
									Toast.LENGTH_LONG).show();

							// auth fail
						} else if (e.getStatusCode() == 21301 // 认证失败
								|| e.getStatusCode() == 21327 // token 过期
						) {
							if (allowAuth) {
								authAndSend(activity, text, picFile);
							} else {
								Log.e(Weibo.class.getName(),
										"" + e.getStatusCode(), e);
								Toast.makeText(IMDroid.getContext(),
										"微博发送失败：需要登录", Toast.LENGTH_LONG)
										.show();
							}

						} else if (e.getStatusCode() == 21321 // 微博应用在未通过审核前需手工允许测试帐号
						) {
							Log.e(Weibo.class.getName(),
									"" + e.getStatusCode(), e);
							Toast.makeText(IMDroid.getContext(),
									"微博发送失败：需要登记测试帐号", Toast.LENGTH_LONG)
									.show();

							// other error
						} else {
							Log.e(Weibo.class.getName(),
									"" + e.getStatusCode(), e);
							Toast.makeText(IMDroid.getContext(),
									"微博发送失败：错误号 " + e.getStatusCode(),
									Toast.LENGTH_LONG).show();
							// 21321 微博应用需要添加测试帐号
						}
					}
				});

			}
		}.start();
	}

	private static void testAndAuth(final Activity activity) {
		final WeiboParameters params = new WeiboParameters();
		params.add("access_token", token.getToken());
		params.add("source", appId);

		new Thread() {
			public void run() {
				WeiboException err = null;
				try {
					HttpManager.openUrl(
							"https://api.weibo.com/2/account/get_uid.json",
							"GET", params, null);
				} catch (WeiboException e) {
					err = e;
				}

				final WeiboException e = err;
				IMDroid.runInMainLooper(new Runnable() {
					public void run() {
						if (e == null) {
							Toast.makeText(IMDroid.getContext(), "微博已登录",
									Toast.LENGTH_LONG).show();
//							IMDroid.setWeiboLogin(true);
						} else if (e.getStatusCode() == 21301
								|| e.getStatusCode() == 21327) {
							authAndSend(activity, null, null);

						} else if (e.getStatusCode() == 21321) {
							Toast.makeText(IMDroid.getContext(),
									"微博登录失败：需要登记测试帐号", Toast.LENGTH_LONG)
									.show();
//							IMDroid.setWeiboLogin(false);
						} else {
							Toast.makeText(IMDroid.getContext(),
									"微博登录失败：错误号 " + e.getStatusCode(),
									Toast.LENGTH_LONG).show();
//							IMDroid.setWeiboLogin(false);
						}
					}
				});
			}
		}.start();
	}

}
